package gitlet;

import javax.swing.JMenuItem;
import javax.swing.JMenu;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JFileChooser;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static gitlet.Utils.join;
import static gitlet.Utils.readContentsAsString;

/**
 * @author 陈恒康
 * @Description The type Repository menu.
 * @date 2023/12/23
 */
public class RepositoryMenu extends JMenu {
    /**
     * Instantiates a new Repository menu.
     *
     * @param branchPanel the branch panel
     * @param repository  the repository
     */
    public RepositoryMenu(JPanel branchPanel, Repository repository) {
        super("Remote");
        JMenuItem pull = new JMenuItem("Pull");
        JMenuItem push = new JMenuItem("Push");
        JMenuItem fetch = new JMenuItem("Fetch");
        JMenuItem cloneButten = new JMenuItem("Clone");
        JMenuItem addRemote = new JMenuItem("AddRemote");
        JMenuItem removeRemote = new JMenuItem("RemoveRemote");
        this.add(push);
        this.add(pull);
        this.add(fetch);
        this.add(addRemote);
        this.add(removeRemote);
        this.add(cloneButten);
        removeRemote.addActionListener(e -> {
            File configFile = join(repository.getGITLET_DIR(), "config");
            if (!configFile.exists()) {
                JOptionPane.showMessageDialog(null, "发生错误: " + "无远程仓库", "警告", JOptionPane.WARNING_MESSAGE);
            } else {
                String s = readContentsAsString(configFile);
                // 使用正则表达式对字符串进行分割
                Pattern p = Pattern.compile("\\[(.*?)\\]");
                Matcher m = p.matcher(s);
                List<String> list = new ArrayList<>();
                while (m.find()) {
                    list.add(m.group(1));
                }
                if (list.isEmpty()) {
                    JOptionPane.showMessageDialog(null, "发生错误: " + "无远程仓库", "警告", JOptionPane.WARNING_MESSAGE);
                } else {
                    String[] result = list.toArray(new String[0]);
                    String input = (String) JOptionPane.showInputDialog(new JPanel(), "请选择远程仓库", "选择仓库", 1, null,
                            result, result[0]);
                    if (input != null) {
                        String keyword = "remote";
                        int firstKeywordIndex = input.indexOf(keyword);
                        String remoteName = input.substring(firstKeywordIndex + keyword.length() + 1);
                        repository.remoteRemove(remoteName);
                    }
                }
            }
        });

        addRemote.addActionListener(e -> {
            String userInput = JOptionPane.showInputDialog("请输入远程仓库名：");
            if (userInput != null && !userInput.isEmpty()) {
                JFileChooser fileChooser = new JFileChooser();
                fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                int returnValue = fileChooser.showOpenDialog(null);
                if (returnValue == JFileChooser.APPROVE_OPTION) {
                    File selectedFile = fileChooser.getSelectedFile();
                    String remoteUrl = selectedFile.getAbsolutePath();
                    String newPath = Paths.get(remoteUrl, userInput).toString();
                    repository.remoteAdd(userInput, newPath);
                }
            }
        });
        fetch.addActionListener(e -> {
            File configFile = join(repository.getGITLET_DIR(), "config");
            if (!configFile.exists()) {
                JOptionPane.showMessageDialog(null, "发生错误: " + "无远程仓库", "警告", JOptionPane.WARNING_MESSAGE);
            } else {
                String s = readContentsAsString(configFile);
                Pattern p = Pattern.compile("\\[(.*?)\\]");
                Matcher m = p.matcher(s);
                List<String> list = new ArrayList<>();
                while (m.find()) {
                    list.add(m.group(1));
                }
                if (list.isEmpty()) {
                    JOptionPane.showMessageDialog(null, "发生错误: " + "无远程仓库", "警告", JOptionPane.WARNING_MESSAGE);
                } else {
                    String[] result = list.toArray(new String[0]);
                    String input = (String) JOptionPane.showInputDialog(new JPanel(), "请选择远程仓库", "选择仓库", 1, null,
                            result, result[0]);
                    if (input != null) {
                        String keyword = "remote";
                        int firstKeywordIndex = input.indexOf(keyword);
                        String remoteName = input.substring(firstKeywordIndex + keyword.length() + 1);
                        String[] branches = repository.getAllBranchFromRemoteName(remoteName);
                        String bInput = (String) JOptionPane.showInputDialog(new JPanel(), "请选择分支", "选择分支", 1, null,
                                branches, branches[0]);
                        if (bInput == null)
                            return;
                        try {
                            repository.fetch(remoteName, bInput);
                            BranchListPanel branchListPanel = new BranchListPanel(repository, branches);
                            branchPanel.removeAll();
                            branchPanel.add(branchListPanel);
                            branchPanel.revalidate();
                            branchPanel.repaint();
                        } catch (IOException ex) {
                            throw new RuntimeException(ex);
                        }
                    }
                }
            }
        });
        /**
         * @Description 这个方法为pull按钮添加了一个ActionListener。它读取配置文件并获取所有远程仓库的列表。如果没有远程仓库，它将显示错误消息。否则，它将提示用户选择一个远程仓库和一个分支，然后从所选的远程仓库和分支拉取更新。
         * @author 陈恒康
         * @date 2023/12/15
         */
        pull.addActionListener(e -> {
            File configFile = join(repository.getGITLET_DIR(), "config");
            if (!configFile.exists()) {
                JOptionPane.showMessageDialog(null, "发生错误: " + "无远程仓库", "警告", JOptionPane.WARNING_MESSAGE);
            } else {
                String s = readContentsAsString(configFile);
                Pattern p = Pattern.compile("\\[(.*?)\\]");
                Matcher m = p.matcher(s);
                List<String> list = new ArrayList<>();
                while (m.find()) {
                    list.add(m.group(1));
                }
                if (list.isEmpty()) {
                    JOptionPane.showMessageDialog(null, "发生错误: " + "无远程仓库", "警告", JOptionPane.WARNING_MESSAGE);
                } else {
                    String[] result = list.toArray(new String[0]);
                    String input = (String) JOptionPane.showInputDialog(new JPanel(), "请选择远程仓库", "选择仓库", 1, null,
                            result, result[0]);
                    if (input != null) {
                        String keyword = "remote";
                        int firstKeywordIndex = input.indexOf(keyword);
                        String remoteName = input.substring(firstKeywordIndex + keyword.length() + 1);
                        String[] branches = repository.getAllBranchFromRemoteName(remoteName);
                        String bInput = (String) JOptionPane.showInputDialog(new JPanel(), "请选择分支", "选择分支", 1, null,
                                branches, branches[0]);
                        try {
                            repository.pull(remoteName, bInput);
                            BranchListPanel branchListPanel = new BranchListPanel(repository, branches);
                            branchPanel.removeAll();
                            branchPanel.add(branchListPanel);
                            branchPanel.revalidate();
                            branchPanel.repaint();
                        } catch (IOException ex) {
                            throw new RuntimeException(ex);
                        }
                    }
                }
            }
        });
        /**
         * @Description 这个方法为push按钮添加了一个ActionListener。它读取配置文件并获取所有远程仓库的列表。如果没有远程仓库，它将显示错误消息。否则，它将提示用户选择一个远程仓库，然后将当前分支的更新推送到所选的远程仓库。
         * @author 陈恒康
         * @date 2023/12/15
         */
        push.addActionListener(e -> {
            File configFile = join(repository.getGITLET_DIR(), "config");
            if (!configFile.exists()) {
                JOptionPane.showMessageDialog(null, "发生错误: " + "无远程仓库", "警告", JOptionPane.WARNING_MESSAGE);
            } else {
                String s = readContentsAsString(configFile);
                Pattern p = Pattern.compile("\\[(.*?)\\]");
                Matcher m = p.matcher(s);
                List<String> list = new ArrayList<>();
                while (m.find()) {
                    list.add(m.group(1));
                }
                if (list.isEmpty()) {
                    JOptionPane.showMessageDialog(null, "发生错误: " + "无远程仓库", "警告", JOptionPane.WARNING_MESSAGE);
                } else {
                    String[] result = list.toArray(new String[0]);
                    String input = (String) JOptionPane.showInputDialog(new JPanel(), "请选择远程仓库", "选择仓库", 1, null,
                            result, result[0]);
                    if (input != null) {
                        String keyword = "remote";
                        int firstKeywordIndex = input.indexOf(keyword);
                        String remoteName = input.substring(firstKeywordIndex + keyword.length() + 1);
                        try {
                            repository.push(remoteName);
                        } catch (IOException ex) {
                            throw new RuntimeException(ex);
                        }
                    }
                }
            }
        });

        cloneButten.addActionListener(e -> {
            File configFile = join(repository.getGITLET_DIR(), "config");
            if (!configFile.exists()) {
                JOptionPane.showMessageDialog(null, "发生错误: " + "无远程仓库", "警告", JOptionPane.WARNING_MESSAGE);
            } else {
                String s = readContentsAsString(configFile);
                Pattern p = Pattern.compile("\\[(.*?)\\]");
                Matcher m = p.matcher(s);
                List<String> list = new ArrayList<>();
                while (m.find()) {
                    list.add(m.group(1));
                }
                if (list.isEmpty()) {
                    JOptionPane.showMessageDialog(null, "发生错误: " + "无远程仓库", "警告", JOptionPane.WARNING_MESSAGE);
                } else {
                    String[] result = list.toArray(new String[0]);
                    String input = (String) JOptionPane.showInputDialog(new JPanel(), "请选择远程仓库", "选择仓库", 1, null,
                            result, result[0]);
                    if (input != null) {
                        String keyword = "remote";
                        int firstKeywordIndex = input.indexOf(keyword);
                        String remoteName = input.substring(firstKeywordIndex + keyword.length() + 1);
                        try {
                            repository.Clone(remoteName);
                            String[] branches = repository.getBRANCH_HEADS_DIR().list();
                            BranchListPanel branchListPanel = new BranchListPanel(repository, branches);
                            branchPanel.removeAll();
                            branchPanel.add(branchListPanel);
                            branchPanel.revalidate();
                            branchPanel.repaint();
                        } catch (IOException ex) {
                            throw new RuntimeException(ex);
                        }
                    }
                }
            }
        });
    }
}